package io;

import java.io.*;
import java.util.Scanner;
/*
* 输入路径,输入查询词,搜索路径内文件中的查询词
* */
public class FileDemo05 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要搜索的路径");
        String path=scanner.next();
        System.out.println("请输入要查询的词");
        String searchword= scanner.next();
        //验证路径是否合法
        File rootfile=new File(path);
        if(!rootfile.isDirectory()){
            System.out.println("当前路径不合法");
            return;
        }
        search(rootfile,searchword);
    }

    private static void search(File rootfile, String searchword) {
        File[] files=rootfile.listFiles();
        if(files==null){
            return;
        }
        for (File file :
                files) {
            if (file.isFile()){
                //读取文件内容并搜索
                matchWord(file,searchword);
            }else {
                //递归搜索子目录
                search(file,searchword);
            }
        }
    }

    private static void matchWord(File file, String searchword) {
        try(Reader reader=new FileReader(file)){
            StringBuilder stringBuilder=new StringBuilder();
            while(true){
                int c= reader.read();
                if(c==-1){
                    break;
                }
                stringBuilder.append((char)c);
            }
            if (stringBuilder.indexOf(searchword)>=0){
                System.out.println("找到了匹配的结果"+file.getAbsolutePath());
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
